import '@/assets/StatusSimple.css'
import usePersonStore from '@/store/person'
import { useShallow } from 'zustand/react/shallow'
function Left() {
    console.log('A组件渲染')
    const { name, age, hobby, setHobbyRap, setHobbyDance } = usePersonStore()
    return (
        <div className="left">
            <h1>A组件</h1>
            <div>
                <h3>{name}</h3>
                <div>年龄：<span>{age}</span></div>
                <div>爱好1：<span>{hobby.sing}</span></div>
                <div>爱好2：<span>{hobby.dance}</span></div>
                <div>爱好3：<span>{hobby.rap}</span></div>
                
                <button onClick={() => setHobbyRap('只因你太美')}>改变爱好rap</button>
                <button onClick={() => setHobbyDance('爵士舞')}>改变爱好dance</button>
            </div>
        </div>
    )
}
function Right() {
    console.log('B组件渲染')
    const { rap, name, basketball, setHobbyBasketball } = usePersonStore(useShallow((state) => ({
        rap: state.hobby.rap,
        name: state.name,
        basketball: state.hobby.basketball,
        setHobbyBasketball: state.setHobbyBasketball
    })))
    return (
        <div className="right">
            <h1>B组件</h1>
            <div>
                <div>姓名：<span>{name}</span></div>
                <div>rap：<span>{rap}</span></div>
                <div>爱好4：<span>{basketball}</span></div>
            </div>
            <button onClick={() => setHobbyBasketball('跳转rap')}>改变爱好basketball</button>
        </div>
    )
}
export default function StatusSimplification() {
  return (
    <>
      <h1>StatusSimplification</h1>
      <div>两个知识点：</div>
      <p>
        一、使用状态选择器，状态选择器可以让我们只选择我们需要的部分状态，这样就不会引发不必要的重渲染。<br/>
          {'const name = useUserStore((state) => state.name)'}<br/>
          {'const rap = useUserStore((state) => state.hobby.rap)'}<br/>
      </p>
      <h2>以下是最佳实践</h2>
      <p>
        二、useShallow()，它的作用是在状态更新的时候，只更新状态选择器选择的状态，不更新其他状态，这样可以避免不必要的重渲染<br/>
        既可以解构，又可以满足只有用到的状态变更，才重新渲染组件
      </p>
      <div style={{display: 'flex'}}>
        <Left />
        <Right />
      </div>
    </>
  )
}